import "./index.scss"
import {View} from "@tarojs/components"
import {observer} from "mobx-react"
import {useContext, useEffect, useState} from "react"
import {useDidHide, useDidShow, useRouter} from "@tarojs/taro"
import {devControllStore} from "./model"
import {uSelectDevControl, exeControlCommand} from "@/api/setting"
import {ControllBtn} from "./components"
import Taro from "@tarojs/taro"

const Devcontroll = ({compDataList}) => {
	let router = useRouter()
	const {updatePageQuery, clearPageQuery, pageQuery} = useContext(devControllStore)

	const [dataSource, setDataSource] = useState<Setting.DevControll[]>([])

	function updatePageDataSource(isReadR = false) {
		//  Taro.showLoading({
		//    title: '加载中'
		//  })
		if (!pageQuery.devId) return
		uSelectDevControl({
			devId: pageQuery.devId
		})
			.then(res => {
				console.log(res.data, "resresresres")
				// res.data.splice(res.data.length - 1, 1)
				console.log(res.data)

				/* 动态存储雨水和污水开关指令  start --------------------- */
				let newRes = compDataList
				newRes.forEach((item, index) => {
					if (item.funName == "雨水控制") {
						item.data.forEach(item1 => {
							switch (item1.controlName) {
								case "雨水开启":
									setRainwaterOpen(item1.controlId)
									break
								case "雨水关闭":
									setRainwaterClose(item1.controlId)
									break
								default:
									break
							}
						})
					} else if (item.funName == "污水控制") {
						item.data.forEach(item1 => {
							switch (item1.controlName) {
								case "污水开启":
									setSewageOpen(item1.controlId)
									break
								case "污水关闭":
									setSewageClose(item1.controlId)
									break
								default:
									break
							}
						})
					} else {
						item.data.forEach(item1 => {
							switch (item1.controlName) {
								case "空调开启":
									setSewageOpen(item1.controlId)
									break
								case "空调关闭":
									setSewageClose(item1.controlId)
									break
								default:
									break
							}
						})
					}

					// 单个开关的指令取出
					// console.log(item, '取出指令')
					let zldata = item.data
					console.log(zldata, "zldata")

					let readOrderLists = readOrderList

					if (isReadR != true) {
						zldata.forEach(async items => {
							if (items.makeProperty == "read") {
								Taro.showLoading({
									title: "读取中"
								})
								await exeControlCommand({controlId: items.controlId})
									.then(readRes => {
										console.log(readRes, "readRes")
										updatePageDataSource(true)
										Taro.hideLoading()
										Taro.showToast({
											title: "读取成功"
										})
									})
									.catch(readError => {
										console.log(readError, "err")
										Taro.hideLoading()
										Taro.showModal({
											title: "提示",
											content: readError.msg,
											success(result) {
												if (result.confirm) {
												} else if (result.cancel) {
												}
											}
										})
									})
							}
						})
					}

					console.log(readOrderLists, "reads")

					zldata.forEach(items => {
						console.log(items, "zldataitem")
						if (items.status != 0) {
							// console.log(item)
							if (items.makeProperty == "close") {
								console.log(items.controlId, "关指令")
								setOneCancelSwitch(items.controlId)
							} else if (items.makeProperty == "open") {
								console.log(items.controlId, "开指令")
								setOneOpenSwitch(items.controlId)
							}
							// switch (items.makeProperty) {
							//   case 'open':
							//
							//     break
							//   case 'close':
							//     break
							//
							//   default:
							//     break
							// }
						}
					})

					console.log(oneOpenSwitch, oneCancelSwitch, "开关指令")

					// if (item.data[0].status == 1 && item.data[1].status == 1) {
					//   setOneOpenSwitch(item.data[0].controlId)
					//   setOneCancelSwitch(item.data[1].controlId)
					// } else {
					//   setOneOpenSwitch(item.data[1].controlId)
					//   setOneCancelSwitch(item.data[2].controlId)
					// }

					if (item.typeFlag == "3") {
						setIsSwitchOrBtn(false)
					}
				})

				/* 动态存储雨水和污水开关指令  end --------------------- */
				// 将拿到的controlId传给数据
				// 雨水---开指令ID  6
				// setRainwaterOpen(res.data[0].data[1].controlId)
				// 雨水---关指令ID  8
				// setRainwaterClose(res.data[0].data[2].controlId)
				// 雨水---开指令ID  7
				// setSewageOpen(res.data[1].data[1].controlId)
				// 雨水---关指令ID  9
				// setSewageClose(res.data[1].data[2].controlId)
				console.log(1)
				console.log(res.data)
				setDataSource(compDataList)
				console.log(2)
				// if(isSwitchOrBtn)

				// console.log(res.data, '123456')
				if (compDataList[0].typeFlag == "1") {
					setOneOrTwoSwitch(true)
					if (compDataList[0].nowStatus == "1") {
						setOneSwitchStatus(true)
					} else {
						setOneSwitchStatus(false)
					}
				} else {
					if (compDataList[0].nowStatus == 1) {
						setRainwaterChecked(true)
					} else {
						setRainwaterChecked(false)
					}
					if (compDataList[1].nowStatus == 1) {
						setSewageChecked(true)
					} else {
						setSewageChecked(false)
					}
					setOneOrTwoSwitch(false)
				}
			})
			.catch(err => {
				setDataSource([])
			})

		// 页面刚开始查询状态
		// exeControlCommand({
		//   controlId:4
		// }).then(res =>{
		//   if(res.msg=='开启中'){
		//     setRainwaterChecked(true)
		//   }else{
		//     setRainwaterChecked(false)
		//   }
		// })

		const newarr = [
			{
				controlId: 1,
				controlCode: "001",
				controlName: "001",
				devId: 1,
				DevControll: "001"
			},
			{
				controlId: 2,
				controlCode: "002",
				controlName: "002",
				devId: 2,
				DevControll: "001"
			},
			{
				controlId: 3,
				controlCode: "003",
				controlName: "003",
				devId: 3,
				DevControll: "001"
			},
			{
				controlId: 4,
				controlCode: "004",
				controlName: "004",
				devId: 4,
				DevControll: "001"
			}
		]

		// setDataSource(newarr)
	}

	// 可以使用所有的 React Hooks
	useEffect(() => {
		console.log("Devcontroll useEffect dataSource", dataSource)

		// setTimeout(() => {

		// }, 1000)
	}, [dataSource])

	// 可以使用所有的 React Hooks
	useEffect(() => {
		console.log("Devcontroll useEffect")
		updatePageDataSource(false)
	}, [pageQuery])
	// 对应 onShow
	useDidShow(() => {
		console.log("Devcontroll useDidShow")
		updatePageQuery(router.params)
		// updatePageDataSource(false)
	})
	// 对应 onHide
	useDidHide(() => {
		console.log("Devcontroll useDidHide")
		clearPageQuery()
	})

	// 是否有读取状态
	const [isRead, setIsRead] = useState(false)

	// 读取指令存储
	const [readOrderList, setReadOrderList] = useState([])

	// 当前雨水开关的标识
	const [rainwaterChecked, setRainwaterChecked] = useState(false)
	// 当前污水开关的标识
	const [sewageChecked, setSewageChecked] = useState(false)

	// 雨水---开指令ID
	const [rainwaterOpen, setRainwaterOpen] = useState(0)
	// 雨水---关指令ID
	const [rainwaterClose, setRainwaterClose] = useState(0)
	// 雨水---开指令ID
	const [sewageOpen, setSewageOpen] = useState(0)
	// 雨水---关指令ID
	const [sewageClose, setSewageClose] = useState(0)

	// 单个开关的指令
	const [oneOpenSwitch, setOneOpenSwitch] = useState(0)
	const [oneCancelSwitch, setOneCancelSwitch] = useState(0)

	// 单个按钮当前是开还是关的标识
	const [oneSwichStatus, setOneSwitchStatus] = useState(false)

	// 判断是单个开关，或者是两个开关的请求的标识
	const [oneOrTwoSwitch, setOneOrTwoSwitch] = useState(false)

	// 判断是开关还是按钮的标识
	const [isSwitchOrBtn, setIsSwitchOrBtn] = useState(true)

	// 单个只开启卡片的是开启还是关闭的状态标识     默认关闭  开启之后不可关闭  再次点击也是关闭状态
	// const [isOnlyOpenCardState, setIsOnlyOpenCardState] = useState(true)

	// 单个只开启卡片点击开始的点击事件
	// const onlyOpenCardClick = () => {
	//   console.log(isOnlyOpenCardState)
	// }
	// 单个只开启卡片点击开始的指令
	const [oneOnlyEnabledInstruction, setOneOnlyEnabledInstruction] = useState(0)

	// 单个只开启卡片点击开始的点击事件
	const onlyOpenCardClick = async (controll: object) => {
		console.log(controll)
		let openControlId = 0
		let openControlName = controll.funName

		controll.data.forEach(item => {
			if (item.status != 0) {
				switch (item.makeProperty) {
					case "open":
						openControlId = item.controlId
						break

					default:
						break
				}
			}
		})
		console.log(openControlId)

		Taro.showModal({
			title: "提示",
			content: `确定要启动${openControlName}检测吗?`,
			async success(result) {
				Taro.showLoading({
					title: "执行中..."
				})
				if (result.confirm) {
					await exeControlCommand({controlId: openControlId})
						.then(res => {
							Taro.hideLoading()
							if (res.result == "error") {
								Taro.showToast({
									title: res.msg,
									icon: "error"
								})
							} else {
								console.log(res)
								Taro.hideLoading()
								Taro.showToast({
									title: "启动完成!"
								})
								updatePageDataSource()
							}

							// if (res.result == 'error') {
							//   Taro.showToast({
							//     title: res.msg
							//   })
							// } else {
							//   Taro.showToast({
							//     title: '启动完成!'
							//   })
							// }
						})
						.catch(err => {
							Taro.hideLoading()
							Taro.showToast({
								title: err.msg
							})
						})
				} else if (result.cancel) {
					Taro.hideLoading()
				}
			}
		})

		setRainwaterChecked(!rainwaterChecked)
		setSewageChecked(!sewageChecked)
		setRainwaterChecked(rainwaterChecked)
		setSewageChecked(sewageChecked)
		setOneSwitchStatus(!oneSwichStatus)
		setOneSwitchStatus(oneSwichStatus)

		updatePageDataSource()
	}

	// 发送指令错误提示函数
	function instructErrorHintFunc() {
		Taro.showModal({
			title: "提示",
			content: `设备不在线，无法执行！`,
			success(result) {
				if (result.confirm) {
				} else if (result.cancel) {
				}
			}
		})
		setRainwaterChecked(!rainwaterChecked)
		setSewageChecked(!sewageChecked)
		setRainwaterChecked(rainwaterChecked)
		setSewageChecked(sewageChecked)
		setOneSwitchStatus(!oneSwichStatus)
		setOneSwitchStatus(oneSwichStatus)
		updatePageDataSource()
	}

	// 控制雨水和污水开关显示的函数----发送请求指令
	async function setRainwaterCheckedFunc() {
		Taro.showLoading({
			title: "执行中..."
		})
		if (oneOrTwoSwitch) {
			if (oneSwichStatus) {
				console.log(111)
				await exeControlCommand({controlId: oneCancelSwitch})
					.then(res => {
						Taro.hideLoading()
						console.log(res)
						Taro.showModal({
							title: "提示",
							content: res.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
						// updatePageDataSource()
					})
					.catch(error => {
						Taro.hideLoading()
						console.log(error)
						Taro.showModal({
							title: "提示",
							content: error.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
						setOneSwitchStatus(!oneSwichStatus)
						setOneSwitchStatus(oneSwichStatus)
						// updatePageDataSource()
					})
			} else {
				console.log(222)
				await exeControlCommand({controlId: oneOpenSwitch})
					.then(res => {
						Taro.hideLoading()
						console.log(res)
						Taro.showModal({
							title: "提示",
							content: res.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
						// updatePageDataSource()
					})
					.catch(error => {
						Taro.hideLoading()
						console.log(error)
						Taro.showModal({
							title: "提示",
							content: error.msg,
							success(result) {
								if (result.confirm) {
									Taro.hideLoading()
								} else if (result.cancel) {
								}
							}
						})
						setOneSwitchStatus(!oneSwichStatus)
						setOneSwitchStatus(oneSwichStatus)
						// updatePageDataSource()
					})
				Taro.hideLoading()
			}
		} else {
			if (rainwaterChecked) {
				exeControlCommand({controlId: rainwaterClose})
					.then(res => {
						exeControlCommand({controlId: sewageOpen})
							.then(() => {
								Taro.hideLoading()
								setRainwaterChecked(!rainwaterChecked)
								setSewageChecked(!sewageChecked)
								// updatePageDataSource()
							})
							.catch(err => {
								Taro.hideLoading()
								instructErrorHintFunc()
							})
					})
					.catch(err => {
						Taro.hideLoading()
						instructErrorHintFunc()
					})
			} else {
				exeControlCommand({controlId: sewageClose})
					.then(() => {
						setRainwaterChecked(!rainwaterChecked)
						setSewageChecked(!sewageChecked)
						exeControlCommand({controlId: rainwaterOpen})
							.then(() => {
								Taro.hideLoading()
								setRainwaterChecked(!rainwaterChecked)
								setSewageChecked(!sewageChecked)
								// updatePageDataSource()
							})
							.catch(err => {
								Taro.hideLoading()
								instructErrorHintFunc()
							})
					})
					.catch(err => {
						Taro.hideLoading()
						instructErrorHintFunc()
					})
			}
		}
		setRainwaterChecked(!rainwaterChecked)
		setSewageChecked(!sewageChecked)
		setRainwaterChecked(rainwaterChecked)
		setSewageChecked(sewageChecked)

		// updatePageDataSource()
	}

	return (
		<View className="container1" style="overflow: auto;">
			{/* <View className="hanzi text-16 font-bold mt-23 mb-14 px-16">功能控制</View>
			<View className="hanzi text-14 text-xx_text mb-14 px-16">
				点击下面的按钮对设备发送相关指令，对设备进行远程操控
			</View> */}
			<View className="p-16 grid grid-cols-2 gap-x-15 gap-y-16" style=" overflow: auto;">
				{/* <view>{dataSource.length}</view> */}
				{/* 111 */}
				{dataSource.map(controll => (
					// <View>{controll.controlName}</View>
					<ControllBtn
						controll={controll}
						rainwaterChecked={rainwaterChecked}
						sewageChecked={sewageChecked}
						setRainwaterCheckedFunc={setRainwaterCheckedFunc}
						setSewageChecked={setSewageChecked}
						setRainwaterChecked={setRainwaterChecked}
						setOneSwitchStatus={setOneSwitchStatus}
						oneSwichStatus={oneSwichStatus}
						oneOrTwoSwitch={oneOrTwoSwitch}
						isSwitchOrBtn={isSwitchOrBtn}
						onlyOpenCardClick={onlyOpenCardClick}
					/>
				))}
			</View>
		</View>
	)
}
export default observer(Devcontroll)
